package com.song.config;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.song.dao.IUser;
import com.song.pojo.UserModel;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import lombok.extern.slf4j.Slf4j;

/**
 * 拦截 /qqlogin
 *
 * @描述
 * @作者 huan
 * @时间 2018年3月3日 - 下午5:57:32
 */
@Slf4j
public class QQLoginFilter extends AbstractAuthenticationProcessingFilter {
    /**
     * 用于发送请求
     */
    private IUser iUser;


    public QQLoginFilter(IUser iUser) {
        super(new AntPathRequestMatcher("/qqlogin", "GET"));
        this.iUser = iUser;
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        String code = request.getParameter("code");

        if (code == null)
            return super.getAuthenticationManager().authenticate(new QQLoginToken(""));
        UserModel userOpenid = iUser.getUserOpenid(code);
        QQLoginToken qqLoginToken = new QQLoginToken("");
        if (userOpenid != null) {
//登录成功
            userOpenid.setPwd("想知道？不可能告诉你的！！");
            qqLoginToken = new QQLoginToken(userOpenid, 1);
            qqLoginToken.setDetails(authenticationDetailsSource.buildDetails(request));


        } else {

            qqLoginToken.setType(2);
        }

        return super.getAuthenticationManager().authenticate(qqLoginToken);
    }


}